//
//  TTComposeController.swift
//  TTWeibo
//
//  Created by 陶宏路 on 16/7/26.
//  Copyright © 2016年 陶路路. All rights reserved.
//

import UIKit
import SVProgressHUD
class TTComposeController: UIViewController ,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{

    lazy var ttHomeModel:TTHomeVcModel = TTHomeVcModel()
    var button:UIButton?
    var image:UIImage?
    private lazy var emoticonView:TTEmoticonView = TTEmoticonView()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
        view.addSubview(composeTextView)
        composeTextView.addSubview(composeCollection)
        view.addSubview(bottomView)
        setUpLayout()
        
    }
    func setUpUI(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didCancelButton")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "didComposeButton")
        
        self.navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
    }
//  Mark：点击取消
    
    func didCancelButton(){
        
        composeTextView.resignFirstResponder()
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func setUpLayout(){
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeCollection.snp_makeConstraints { (make) -> Void in
            
            make.width.height.equalTo(SCREENW - 20)
            make.centerX.equalTo(composeTextView)
            make.top.equalTo(composeTextView).offset(150)
        }
        
        bottomView.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        bottomView.buttonBlock = {[weak self](type) in
            
            switch type{
                
            case .Picture:
                self!.selectorPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("😊")
                self?.switchKeyBoard()
                
            case .Add:
                print("➕")
            }
        }
        
//    监听键盘点击
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
//  mark：监听按钮点击 
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectorPicture:", name: "didPictureButton", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEmotionButton:", name: "didEmotionButton", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didDeleteButton", name: "didDeleteButton", object: nil)
    }
    
// mark 点击表情按钮
    
    func didEmotionButton(info:NSNotification){
        
        guard let model = info.object as? TTEmoticonsModel else{
            
            return
        }
        
        if model.type == "1"{
            
            let emoji = (model.code ?? "" as NSString).emoji()
            
         composeTextView.insertText(emoji)
            
        }else{
            
//            获取 textView的富文本
            let attribut = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
//            创建文本附件
//            let attr = NSTextAttachment()
//            设置图片
//            attr.image = UIImage.getImageWithBoundle(model.path)
////            计算行高
//            let emotionHight = composeTextView.font?.lineHeight
////            设置bounds
//            attr.bounds = CGRectMake(0, -4, emotionHight!, emotionHight!)
////            不可变富文本
//            let attibuteString = NSAttributedString(attachment: attr)
            
            
            let attrbuteString = NSAttributedString(model: model, emotionHight: composeTextView.font?.lineHeight)
//            获取光标选中区域
            var selectRange = composeTextView.selectedRange
//            在原有富文本中插入新的富文本
            attribut.replaceCharactersInRange(selectRange, withAttributedString: attrbuteString)
//            设置属性
            attribut.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: attribut.length))
//            赋值
            composeTextView.attributedText = attribut
//            重新设置 光标位置
            selectRange = NSRange(location: selectRange.location + 1, length: 0)
        }
        
            textViewDidChange(composeTextView)
        
        
    }
// mark 点击后退按钮
    
    func didDeleteButton(){
        
        composeTextView.deleteBackward()
    }
    
// Mark 监听键盘弹出
    
    func keyboardWillChangeFrame(info:NSNotification){
        
        guard let userInfo = info.userInfo else{
            
            return
        }
        
//        获取键盘弹出时间
        
        let time = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        
//        获取键盘弹出的frame

        let content = userInfo["UIKeyboardFrameEndUserInfoKey"] as? NSValue
//        获取键盘变化
 
        print(content)
        let rect = content?.CGRectValue()
        self.bottomView.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset((rect?.origin.y)! - SCREENH)
        }
        UIView.animateWithDuration(NSTimeInterval(time)) { () -> Void in
            
            self.bottomView.layoutIfNeeded()
        }
    }
    
//   点击表情
    func switchKeyBoard(){
        
        if composeTextView.inputView == nil{
            
            composeTextView.inputView = emoticonView
            bottomView.isEmoji = false
            
        }else{
            
            composeTextView.inputView = nil
            
            bottomView.isEmoji = true
        }
        
        composeTextView.reloadInputViews()
        composeTextView.becomeFirstResponder()
        
    }
    
    
// mark : 实现监听方法 打开相册
    
    func selectorPicture(){

        pickerController.sourceType = .PhotoLibrary
        
        [self .presentViewController(pickerController, animated: true, completion: { () -> Void in
            
            
        })]
    }
    
    func selectorPicture(info:NSNotification){
        
        button = info.object as? UIButton
        pickerController.sourceType = .PhotoLibrary
        
        [self .presentViewController(pickerController, animated: true, completion: { () -> Void in
            
            
        })]
    }

    
//  mark : 利用富文本 自定义navigationItem 的 titleView
    
    lazy var titleView:UILabel = {
        let title = UILabel()
        let text = "发微博\n\(name)"
        let attr = NSMutableAttributedString(string: text)
        let range = (text as NSString).rangeOfString(name)
        attr.addAttributes([NSForegroundColorAttributeName:UIColor.orangeColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        title.numberOfLines = 0
        title.attributedText = attr
        title.textAlignment = .Center
        title.sizeToFit()
        return title
    }()
    
    lazy var composeTextView:TTComposeTextView = {
        let compose = TTComposeTextView()
        compose.alwaysBounceVertical = true
        compose.font = UIFont.systemFontOfSize(20)
        compose.delegate = self
        return compose
    }()
    
    lazy var composeCollection :TTComposeCollection = TTComposeCollection()
    
    lazy var bottomView : TTBottomView = TTBottomView()
    
    lazy var pickerController:UIImagePickerController = {
        let picker = UIImagePickerController()
        picker.delegate = self
        return picker
    }()
    
   
    
// mark : UIImagePickerControllerDelegate 代理方法 选取图片
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
  
//   点击按钮更换图片
        
        let selectorImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage;
        
        if button != nil && button?.tag !== 10086{
            
            print(button?.tag)
            
            button?.setImage(selectorImage, forState: UIControlState.Normal)
            
            composeCollection.imageArray[(button?.tag) ?? 0] = selectorImage
            
            button = nil
            
        }else{
            
            if button != nil{
                
                button = nil
            }
            
            if composeCollection.imageArray.count == 9{
                
        
                composeCollection.imageArray[8] = selectorImage
                
            }else{
                
                composeCollection.imageArray.append(selectorImage)
            }
            
            composeCollection.reloadData()
            
        }
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
// mark: UITextView 代理方法
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        composeTextView.hiddenText(textView.hasText())
    }
    
// Mark: UIScrollView 代理方法
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
         self.composeTextView.resignFirstResponder()
    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)

    }
    
//   点击发布按钮
    
    func didComposeButton(){
        
//    遍历富文本
        var attrString = ""
        
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            
//            表示输入的是文本附件
            if let attr = result["NSAttachment"] as? TTTextAttachment{
                
                attrString += attr.emotionModel?.chs ?? ""
                
            }else{
                
                let string = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                attrString += string
            }
            
            
        }
        
        composeCollection.imageArray.count > 0 ? upload(attrString) : update(attrString)
    }
    
}

extension TTComposeController{
    
    func update(status:String){
        
        TTNetworkingTools.sharedNetworkManager.composeData(status, success: { (responseObject) -> () in
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            
                self.dismissViewControllerAnimated(true, completion: nil)
        })
            }) { (error) -> () in
                
               SVProgressHUD.showSuccessWithStatus("发布失败")
        }

    }
    
    func upload(status:String){
        
        TTNetworkingTools.sharedNetworkManager.uploadDate(status, imageArray: composeCollection.imageArray, success: { (responseObject) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                
                self.dismissViewControllerAnimated(true, completion: nil)
            })
            
            }) { (error) -> () in
                
            SVProgressHUD.showSuccessWithStatus("发布失败")
        }
    }
}
